﻿using Datav.Design.Datas.Pocos;
using Datav.Design.IService;
using WorldDesign.Datas;
using XCode;
using Zdap.Common;
using Zdap.Common.AutoMapper;
using Zdap.Common.Extensions;
using Zdap.Common.IdGenerate;
using Zdap.XCode.Service;

namespace Datav.Design.Service
{

    /// <summary>
    ///
    /// </summary>
    public class ScreenService : IScreenService
    {
     
        ///
        public async Task<ResponseContext<long>> Save(ScreenDto model, UserTicket currentUser, bool isCopy = false)
        {
            var restult = new ResponseContext<long>();
            var project = model.Screen.MapTo<Project>();
            model.Screen.Config = model.Config;
            model.Screen.Config.variables = model.Variables;
            if (project.Id == 0 || isCopy)
                project.Id = IdWorker.NextId();
            if (CommonService.IsJsonField(model.Screen))
                CommonService.LoadFieldsJsonCovertString(project, model.Screen);
            var comsList = new List<ProjectComs>();
            var filterList = new List<ProjectFilter>();
            int index = 0; // 初始化序号
            var keys = new Dictionary<long, long>();

            model.Coms.Recursive(x => x.Children, (current, parent) =>
            {
                var parentName = parent?.Name ?? "无";
                // 对象映射
                var com = current.MapTo<ProjectComs>();
                // 节点ID处理
                if (com.Id == 0 || isCopy)
                    com.Id = IdWorker.NextId();
                if (isCopy)
                {
                    keys.Add(current.Id, com.Id);
                }
                // 设置父节点ID（parent可能为null）
                if (parent != null)
                {
                    com.ParentId = (parent.Id);
                }
                if (com.ParentId != 0 && isCopy)
                {
                    if (keys.TryGetValue(com.ParentId, out long parentId))
                    {
                        com.ParentId = parentId;
                    }
                }
               
                var path = (parent == null ? current.Id : $"{(parent).Paths.TrimEnd(',')},{current.Id}") + ",";
                if (current.Type == "subCom")
                {
                    path = $"{current.ParentId},{current.Id}" + ",";
                }
                current.Paths = path;
                com.Paths = path;
                // 设置项目属性
                com.ProjectId = project.Id;
                com.Sort = ++index;
                // 特殊类型处理
                if (com.Type != "layer" && com.ApiData != null)
                {
                    current.ApiData.source.comId = com.Id;
                }
                // JSON字段处理
                if (CommonService.IsJsonField(current))
                    CommonService.LoadFieldsJsonCovertString(com, current);
                // 租户信息设置
                CommonService.SetCommonPropertyTenantId(com, currentUser);
                // 添加到结果集
                comsList.Add(com);
                return $"{current.Name} (父节点: {parentName})";
            }
             );

            model.DataFilters.Foreach(async (item, i) =>
            {
                var filter = item.MapTo<ProjectFilter>();
                if (filter.Id == 0 || isCopy)
                    filter.Id = IdWorker.NextId();
                filter.ProjectId = project.Id;
                filter.Sort = (i + 1);
                if (CommonService.IsJsonField(item))
                    CommonService.LoadFieldsJsonCovertString(filter, item);
                CommonService.SetCommonPropertyTenantId(filter, currentUser);
                filterList.Add(filter);
            });

            using (var tran1 = Project.Meta.CreateTrans())
            {
                project.Upsert(CommonService.GetEntityDataColumn<Project>());
                comsList.Upsert(CommonService.GetEntityDataColumn<ProjectComs>());
                filterList.Upsert(CommonService.GetEntityDataColumn<ProjectFilter>());
                tran1.Commit();
            }

            return await Task.FromResult(restult.SetSuccess(project.Id));
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public async Task<ResponseContext<bool>> Delete(long id, UserTicket currentUser)
        {
            using (var tran1 = Project.Meta.CreateTrans())
            {
                var projects = await Project.FindAllAsync(Project._.Id == id & Project._.IsDelete == 0);
                var coms = await ProjectComs.FindAllAsync(ProjectComs._.ProjectId == id & ProjectComs._.IsDelete == 0);
                var filters = await ProjectFilter.FindAllAsync(ProjectFilter._.ProjectId == id & ProjectFilter._.IsDelete == 0);

                projects.Delete();
                coms.Delete();
                filters.Delete();

                //projects.Upsert(CommonService.GetEntityDataColumn<Project>());
                //coms.Upsert(CommonService.GetEntityDataColumn<ProjectComs>());
                //filters.Upsert(CommonService.GetEntityDataColumn<ProjectFilter>());

                tran1.Commit();
            }
            return new ResponseContext<bool>(CommonConstants.SuccessCode, "", true);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="screenId"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public async Task<ResponseContext<ScreenDto>> GetScreen(long screenId, UserTicket currentUser)
        {
            var result = new ResponseContext<ScreenDto>();
            //var screenDto = new ResponseContext<ScreenDto>();
            var project = await Project.FindAsync(Project._.Id == screenId & Project._.IsDelete == 0);
            if (project == null)
            {
                return await Task.FromResult(result.SetError("大屏不存在！"));
            }
            var coms = await ProjectComs.FindAllAsync(ProjectComs._.ProjectId == screenId & ProjectComs._.IsDelete == 0);

            var filters = await ProjectFilter.FindAllAsync(ProjectFilter._.ProjectId == screenId & ProjectFilter._.IsDelete == 0);
            var dto = new ScreenDto();
            dto.Screen = project.MapTo<ProjectModelDto>();
            // 处理dto JOSN转string保存
            if (CommonService.IsJsonField(dto.Screen))
                CommonService.LoadFieldsStringCovertJson(project, dto.Screen);
            dto.Config = dto.Screen.Config;
            dto.Variables = dto.Screen.Config.variables;


            var comList = coms.Select(s =>
            {
                var item = s.MapTo<ComsModelDto>();
                // 处理dto JOSN转string保存
                if (CommonService.IsJsonField(item))
                    CommonService.LoadFieldsStringCovertJson(s, item);
                return item;
            });

            //comList.ToTree<ProjectComsModelDto>();//

            //dto.Coms = TreeBase.CreateTree(comList.ToList()).OrderBy(s => s.Sort);

            dto.Coms = comList.ToTree(
                      idSelector: d => d.Id,
                      parentIdSelector: d => d.ParentId,
                      childrenSetter: (parent, children) => parent.Children = children
                  );


            //var results = comList.TreeExtensions(d => d.Id, d => d.ParentId,
            //     (parent, children) => parent.Children = children
            //   );
            //dto.Coms = results.ToList();
            dto.DataFilters = coms.Select(s => s.MapTo<ProjectFilterModel>());

            return await Task.FromResult(result.SetSuccess(dto));
        }

    }
}